import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('./picture/flower_rgb.png', 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
count = np.zeros(256, np.float)
for i in range(img.shape[0]):
    for j in range(img.shape[1]):
        count[int(gray[i, j])] += 1 # 统计该像素出现的次数
count = count / (img.shape[0] * img.shape[1]) # 得到概率
x = np.linspace(0,255,256)
plt.bar(x, count,color = 'b')
plt.show()


# 计算累计概率

for i in range(1,256):
    count[i] += count[i - 1]
# 映射
map1 = count * 255
for i in range(img.shape[0]):
    for j in range(img.shape[1]):
        p = gray[i, j]
        gray[i, j] = map1[p]
cv2.imshow('gray', gray)
cv2.waitKey(0)
